<?php
/**
 * file video.php
 * Created on 2015-3-25 下午12:41:59 
 * Create by xiweijie
 */
namespace haibao\cms\business;

use \haibao\cms\data\Video as VideoData;
use haibao\cms\business\BusinessException;

class Video extends \haibao\cms\business\Base{
    
	public static function getNewFiveVideos(){
		$data = new VideoData();
		return $data->getNewFiveVideos();
	}
	
    public static function getVideoUrl($file,$videoFile,$videoId){
        $videoNewUrlArr = $videoOldUrlArr  = $videoIdOldArr = $videoIdNewArr = $videoList = array();
        $video = new \haibao\cms\cache\Video();

        /* 开始上传文件，删除垃圾数据 chunk为0 */
        if($videoFile['chunk']==0){
            $videoList = $video->getVideoUrl($videoId);
            if($videoList){
                self::delWastedata($videoId,$videoList);
                $video->delVideoUrl($videoId);
            }
        }
        
        $storagePath = self::getUploadStorageVideoPath($file['name']);
        self::getFullVideoUrl();
        if(!$file['tmp_name']){
            throw new BusinessException('临时文件不存在！重新上传');
        }
        self::generateVideo($storagePath, file_get_contents($file['tmp_name']));
        
        $videoNewUrlArr['userId'] = self::getCurrentUser()->Id;
        $videoNewUrlArr['chunk'] = $videoFile['chunk'];
        $videoNewUrlArr['url'] = $storagePath;
        
        $video->setVideoUrl($videoId,$videoNewUrlArr);
        
        $video->setVideoTrunk($videoId,$videoFile['chunks']);
        
        $videoIdOldArr = $video->getVideoId();
        $videoIdNewArr['fileName'] = $file['name'];
        $videoIdNewArr['videoId'] = $videoId;
        array_push($videoIdOldArr, $videoIdNewArr);
        $video->setVideoId($videoIdOldArr);
        
        if($videoFile['chunk']+1 == $videoFile['chunks']){
            self::addVideoFile($videoId);
        }
        
        return $videoNewUrlArr;
    }
    
    public static function saveUpload($file){
    	$basePath = '/videostore/focus/'.date('Y').DIRECTORY_SEPARATOR;
    	$fullPath = $basePath.microtime(true);
    	$extension = pathinfo($file['name']);
    	$fullPath .= '.' . strtolower(isset($extension['extension']) ? $extension['extension'] : 'mp4');
    	$path = str_replace(array('/', '\\'), '/', $fullPath);
    	$videoData = new VideoData();
    	$savePath = \haibao\frame\Environment::path().$path;
    	\haibao\cms\business\ImageLibrary::createDir($savePath);
    	move_uploaded_file($file['tmp_name'],$savePath);
    	return $path;
    }
    
    private static function delWastedata($videoId,$videoList){
        foreach ($videoList as $k=>$v){
            $path = \haibao\frame\Environment::path().$v['url'];
            file_exists($path)?unlink($path):'';
        }
    }
    
    
    private static function addVideoFile($videoId){
        $videoData = new VideoData();
        $videoOne =$videoData->getVideoFile($videoId);
        if($videoOne){
            $videoData->updateVideoFile($videoId);
        }else{
            $videoData->addVideoFile($videoId);
        }
        
    } 
    /**
     * 获取要上传文件的存储路径
     * @return string /uploadvideo/2014/1230/1419842617.9557.mp4
     */
    public static function getUploadStorageVideoPath($orgionName){
        
        $basePath = \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::VIDEO_UPLOAD_BASE_PATH).'temp'.DIRECTORY_SEPARATOR.date('Y').DIRECTORY_SEPARATOR.date('md').DIRECTORY_SEPARATOR.microtime(true);
        $extension = pathinfo($orgionName);
        $basePath .= '.' . strtolower(isset($extension['extension']) ? $extension['extension'] : 'mp4');
        return str_replace(array('/', '\\'), '/', $basePath);
        
    }
    
    public static function getFullVideoUrl(){
        $path = \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::VIDEO_UPLOAD_BASE_PATH).date('Y').DIRECTORY_SEPARATOR.microtime(true);
        $savePath = self::getSaveImagePath(str_replace(array('/', '\\'), '/', $path));
        self::createDir($savePath);
    }
    
    public static function generateVideo($path, $stream){
        $savePath = self::getSaveImagePath($path);
        self::createDir($savePath);
        file_put_contents($savePath, $stream, LOCK_EX);
    }
    /**
     * 获取文件保存路径
     */
    public static function getSaveImagePath($path){
        $path = '/'. ltrim($path,'/');
        return \haibao\frame\Environment::path() . $path;
    }
    /**
     * 创建文件保存路径
     */
    public static function createDir($path){
        $path = pathinfo( $path );
        if(!is_writable($path['dirname'])){
            $oldumsk = umask(0);
            !is_dir($path['dirname']) ? @mkdir($path['dirname'], 750, true) : '';
            umask($oldumsk);
        }
        //return is_writable($path['dirname']) ?: mkdir($path['dirname'], 750, true);
    }
    
    public static function getVideoFile($videoId){
        $data = new VideoData();
         
        return $data->getVideoFile($videoId);
    }
    
    public static function searchIdsByKeywordFilter($filter){
    	$data = new VideoData();
    	
    	return $data->searchIdsByKeywordFilter($filter);
    }
	
    public static function addVideo($model){
        self::checkOperation(self::FUNC_CODE_VIDEO_ADD);
        self::checkFormData($model);
        
        $tagIdList = self::getTagIdList($model);
        
        $videoData = new VideoData();
        $videoData->addVideo($model,$tagIdList);
        
        if(!empty($model->VideoUrlForH5) && $model->Published == 1){
            $channelTagId = '';
            if(!empty($model->VideorelTagModel) && !empty($model->VideorelTagModel[0]->TagId)){
                $tagInfo = \haibao\cms\business\Tag::getTagById($model->VideorelTagModel[0]->TagId);
                $channelTagId = $tagInfo->TopId;
            }
            if(empty($model->UserName)){
                $model->UserName = self::getCurrentUser()->RealName;
            }
            $videoData->addVideoWap($model,$channelTagId);
        }
        
        self::saveOperateHistory(self::FUNC_CODE_VIDEO_ADD, $model->toArray());
    }
    
    public static function updateVideoById($model){
        self::checkOperation(self::FUNC_CODE_VIDEO_SAVE);
        self::checkFormData($model);
        $model->LastModifyUser = self::getCurrentUser()->Id;
        $model->LastModifyTime = new \DateTime();
        
        $tagIdList = self::getTagIdList($model);
       
        $videoData = new VideoData();
        $videoData->updateVideoById($model,$tagIdList);
        
       
        $channelTagId = '';
        if(!empty($model->VideorelTagModel) && !empty($model->VideorelTagModel[0]->TagId)){
            $tagInfo = \haibao\cms\business\Tag::getTagById($model->VideorelTagModel[0]->TagId);
            $channelTagId = $tagInfo->TopId;
        }
        if(empty($model->UserName)){
            $model->LastModifyUser = self::getCurrentUser()->Id;
            $model->UserName = self::getCurrentUser()->RealName;
        }
        $videoData->addVideoWap($model,$channelTagId);
//         else{
//             $videoData->updateVideoStatus($model->Id);
//         }
        
        self::saveOperateHistory(self::FUNC_CODE_VIDEO_SAVE, $model->toArray());
    }
    
    
    
    public static function deleteVideoById($id){
        self::checkOperation(self::FUNC_CODE_VIDEO_DEL);
        
        if(!$id){
            throw new BusinessException('视频Id不能为空',self::DATA_EMPTY_ID);
        }
        $videoData = new VideoData();
        $arrSet = array();
        $arrSet['Status']  = \haibao\cms\model\data\Video::STATUS_DELETE;
        $arrSet['LastModifyTime'] = new \DateTime();
        $videoData->updateById($id,$arrSet);
        
        //操作聚合记录
        $data = new \haibao\cms\data\PolymerInfo();
        $data->updatePolymarInfo($id,\haibao\cms\model\data\PolymerInfo::OBJECT_TYPE_VIDEO,array('Status'=>\haibao\cms\model\data\PolymerInfo::STATUS_DEL));
        
        self::saveOperateHistory(self::FUNC_CODE_VIDEO_DEL, array('Id' =>$id));
    }
    
    public static function deleteVideoFileById($videoId){
        $videoData = new VideoData();
        $videoData->deleteVideoFileById($videoId);
    }
    
    public static function getVideoListByFilter($query){
        $videoData = new VideoData();
        return $videoData->getAll($query);
    }
    
    public static function getVideoByid($id){
        $videoData = new VideoData();
        return $videoData->getVideoById($id);
    }
    
    public static function getClickCommentNumByVideoIds($videoIds){
    	$videoData = new VideoData();
    	return $videoData->getClickCommentNumByVideoIds($videoIds);
    }
    
    public static function updateEditClickNumById($videoId, $num) {
    	$videoData = new VideoData();
    	$videoData->updateEditClickNumById($videoId, $num);
    }
    
    public static function updateCommentNum($videoId,$num){
    	if(!$videoId){
    		throw new BusinessException('视频Id不能为空',self::DATA_EMPTY_ID);
    	}
    	$videoData = new VideoData();
    	$videoData->updateVideoCommentNum($videoId,$num);
    }
    
    public static function subtractCommentNum($videoId){
    	if(!$videoId){
    		throw new BusinessException('视频Id不能为空',self::DATA_EMPTY_ID);
    	}
    	$videoData = new VideoData();
    	$videoData->subtractCommentNum($videoId);
    }
    
    private static function checkFormData($model){
        if(empty($model->CategoryId)){
            throw new BusinessException('栏目不能为空！',self::DATA_EMPTY);
        }
        if(empty($model->Title)){
            throw new BusinessException('标题不能为空！',self::DATA_EMPTY);
        }
        if(empty($model->VideoUrl)){
            throw new BusinessException('视频链接不能为空！',self::DATA_EMPTY);
        }
        if(empty($model->PublishDate)){
            throw new BusinessException('发布时间不能为空！',self::DATA_EMPTY);
        }
        if(empty($model->VideorelTagModel)){
            throw new BusinessException('标签不能为空！',self::DATA_EMPTY);
        }
    }
    
    public  static function getVideoNum($videoPropertyFilter){
        $videoData = new VideoData();
        return $videoData->getAll($videoPropertyFilter);
    }
    
    public static function getOneById($videoId){

    	if(empty($videoId)){
    		throw new BusinessException('视频ID不存在！',self::DATA_EMPTY);
    	}
    	$videoData = new VideoData();
    	return $videoData->getOneById($videoId);
    }
    public static function getVideoByids($videoIds,$isMessage = false){
    	
    	$videoArr = array();
    	if(empty($videoIds)){
    		throw new BusinessException('视频ID不存在！',self::DATA_EMPTY);
    	}
    	$filter = new \haibao\cms\model\filter\Video();
    	$filter->where(\haibao\cms\model\filter\Video::CONDITION_FIELD_NAME_ID,\haibao\frame\data\query\Condition::CONDITION_IN,$videoIds);

    	$videoData = new VideoData();
    	$videoList = $videoData->getAll($filter);
    	foreach($videoList as $list){
    	    if($isMessage){
    	        $videoArr[$list->Id]['Title'] =  $list->Title;
    	        $videoArr[$list->Id]['Url'] =  \haibao\classlibrary\www\Config::getConfig(\haibao\classlibrary\www\Config::CLASSLIBRARY_CONFIG_HOST_VIDEO)."/play/".$list->Id.".htm";
    	    }else{
    	        $videoArr[$list->Id] = $list;
    	    } 
    	}
    	return $videoArr;
    }
    
    public static function getVideoPublishTimeByids($videoIds){
        $videoData = new VideoData();
        return $videoData->getVideoPublishTimeByids($videoIds);
    }

    private static function getTagIdList($model){
    	$tagIdList = array();
    	if(!empty($model->VideorelTagModel) && $model->Published == 1){
    		$tagIds = array();
    		foreach($model->VideorelTagModel as $videoTag){
    			$tagIds[] = $videoTag->TagId;
    		}
    		if($tagIds){
    			$tagIdList = \haibao\cms\business\Tag::loopGetParentTag($tagIds);
    		}
    	}
    	 
    	return $tagIdList;
    }
    
    
    public static function addVideoFileLog($videoId){
        $videoData = new VideoData();
        $userId = \haibao\www\sites\common\Auth::getUserIdByCookie();
        $videoData->addVideoFileLog($videoId,$userId);
    }
}